package com.backend.help.controller;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import com.github.xiaoymin.knife4j.core.util.StrUtil;
import com.framework.redis.service.RedisService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 描述：
 * 查询配置文件
 *  验证配置文件是否读取和正确
 *   访问http://127.0.0.1:8234/di/config/get
 * @author xianggj
 * @Date 2021/11/16 15:00
 **/
@Controller
@RequestMapping("config")
@ApiSort(2)
@Api(value = "配置验证", tags="配置验证")
public class ConfigController {

    @Value("${spring.cloud.nacos.config.server-addr:127.0.0.1:8848}")
    private String serverAddr;

    @Value("${spring.cloud.nacos.config.namespace:}")
    private String namespace;

    @Autowired
    private RedisService redisService;


    /**
     *
     * @return
     */
    @RequestMapping(value = "/redis", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查看redis值",notes = "不输入key则查询所有key，输入key查询Key值,只能查看String类型", httpMethod = "GET")
    @ApiImplicitParam(name = "key",value="键值",required = false)
    public String getRedis(String key) throws Exception {
        if (StrUtil.isBlank(key)){
            Set<String> keys = redisService.allKeys();
            return StringUtils.join(keys, ",");
        }
        return redisService.get(key);
    }

    /**
     *
     * @return
     */
    @RequestMapping(value = "/get", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "配置验证",notes = "输入配置文件参数 验证配置是否加载，命名空间采用配置空间", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dataId",value="文件名称",required = true),
            @ApiImplicitParam(name = "group",value="组",required = false, defaultValue = "KCS_GROUP"),
            @ApiImplicitParam(name = "key",value="配置项名称, 不填加载所有",required = false)
    })
    public String get(String dataId, String group, String key) throws NacosException, InterruptedException {
        if (StrUtil.isBlank(group)){
            group = "KCS_GROUP";
        }
        Properties properties = new Properties();
        properties.put(PropertyKeyConst.SERVER_ADDR, serverAddr);
        //命名空间只能输入id  不能输入名称
        if (StrUtil.isNotBlank(namespace)){
            properties.put(PropertyKeyConst.NAMESPACE, namespace);
        }
        ConfigService configService = NacosFactory.createConfigService(properties);
        //5秒延迟
        String content = configService.getConfig(dataId, group, 5000);
        System.out.println(content);
        if (StrUtil.isBlank(key)){
            return content;
        }
        if (StrUtil.isBlank(content)){
            return content;
        }
        String[] keyVues = StringUtils.split(content, "\n");
        Map<String, String> map =Arrays.stream(keyVues)
                .filter(e -> StrUtil.isNotBlank(e) && e.contains("=") && !e.trim().startsWith("#"))
                .map(e -> {
                    String[] keyVue = StringUtils.split(e, "=");
                    return keyVue;
                }).collect(Collectors.toMap(e -> e[0], e -> e[1]));
        if (map.containsKey(key)){
            return map.get(key);
        }
        return "";
    }

}
